define(function(require, exports, module) {

	var $ = require('jquery');
	require('artTemplate/artTemplate/2.0.1/template.js');
	require('../util/jquery.icheck');
	require('jquery/jquery-form/1.0.0/jquery.form.js');
	require('jquery/jquery-json/2.4.0/jquery.json.js');
	require('jquery/jquery-validation/1.11.0/jquery.validate');
	require('jquery/jquery-validation/1.11.0/messages_zh');
	require('jquery/jquery-file-upload/8.8.5/vendor/jquery.ui.widget.js');
	require('jquery/jquery-file-upload/8.8.5/jquery.iframe-transport.js');
	require('jquery/jquery-file-upload/8.8.5/jquery.fileupload.js');
	require('spin/1.3/spin.js');
	require('jbox');
	var List = require('../util/list');

	exports.options = {
		listLink : '',
		listParams : '',
		pageLink : '',
		pageParams : ''
	};

	uid = $g_user.id;
	$("#userId").val(uid);

	var flag='';
	var token_qq="";
	var token_webo="";
	var qq_bindtype='';
	var webo_bindtype='';
	var token="";
	var bindtype='';
	exports.laoding=function(e){
		var opts = {  
				  lines: 17, // 菊花瓣的数目  
				  length: 7, // 菊花瓣的长度  
				  width: 4, // 菊花瓣的宽度  
				  radius: 10, // 菊花中心的半径  
				  corners: 1, // 菊花瓣的圆滑度(0--1)  
				  rotate: 0, // 让菊花旋转的角度  
				  color: '#000', // 菊花的颜色  
				  speed: 1.6, // 菊花旋转的速度  
				  trail: 58, // 菊花旋转时的余辉  
				  shadow: false, // 是否需要菊花的阴影  
				  hwaccel: false, // 是否需要菊花高速旋转(硬件加速)  
				  className: 'spinner', // 菊花的classname  
				  zIndex: 2e9, // 菊花的z-index值  
				  top: 'auto', // 菊花相对定位的top  
				  left: 'auto' // 菊花相对定位的left  
				};  
				var target = document.getElementById(e);  
				var spinner = new Spinner(opts).spin(target);
				target.appendChild(spinner.el); 
	};
	
	// 三角型指示显示
	$('#profile>.nav-tabs>li').click(function() {
		$(this).addClass('active').siblings().removeClass('active');
	});

	//tab切换样式
	$('#set-tab a').click(function(e) {
		e.preventDefault();
		$(this).tab('show');
	});
	// 验证
	$("#pwdSet").validate({
		onkeyup:false,
		rules : {
			oldPassword : {
				required : true,
			},
			newPassword : {
				required : true
			},
			rePassword : {
				required : true,
				equalTo:"#newPassword"
			}		
		},
	messages:{
		oldPassword:{
			remote:"原密码错误！",
		},
		newPassword :"请输入新密码！",
		rePassword:{
			required: "请输入确认密码！",
			equalTo: "确认密码与新密码不同！"
		}
	}
	});
	
	var show = function(divID) {
		if (divID != null && divID != "") {
			var v = document.getElementById(divID);
			if (v.style.display == "none") {
				v.style.display = "block";
			}
		}
	};

	var hiden = function(divID) {
		if (divID != null && divID != "") {
			var v = document.getElementById(divID);
			if (v.style.display == "block") {
				v.style.display = "none";
			}
		}
	};
	
	//获取三方绑定信息
//	exports.getBind=function(token){
//		var posting = $.post($CONFIG.base_url + "/third/get_user_info",{url: 'https://api.weibo.com/2/users/show.json?access_token='+token});
//		posting.done(function(data){
//			//console.log($.toJSON(data));
//		});
//	};
	//获取qq三方信息
//	exports.getQQBind=function(token){
//		 $.ajax({
//			  type: 'GET',
//			  url: 'https://graph.qq.com/oauth2.0/me?access_token='+token,
//			  async: false,
//			  dataType: "jsonp",
//			  jsonp: "callback",//传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
//			  jsonpCallback:"callback",
//			  success: function(data){
//				  //console.log("callback;;;;;;;;"+$.toJSON(data));
//				  //console.log(data.client_id);
//				  //console.log(data.openid);
//				  $.ajax({  
//	                  type: 'GET',  
//	                  url:'https://graph.qq.com/user/get_user_info',  
//	                  data:{'oauth_consumer_key':data.client_id,'access_token':token,'openid':data.openid},  
//	                  async: false,  
//	                  dataType: "json",  
//	                  success: function(e){
//	                	  var tx=e.figureurl_qq_1;
//	                      var name=e.nickname;
//	                      $("#third-qq-bind img").attr({src:tx});
//	                      $("#third-qq-bind span").text(name);
//	                  }  
//	            });  
//			 }
//		  });
//	};
//	exports.getBind();
	//获取三方绑定列表
	exports.checkToken=function(){
		var getting = $.get($CONFIG.base_url + "/api/user/get/bind/list",{"uid":uid});
		getting.done(function(data) {
			if(data.result.length!="0"){
			if(data.result.length=="2"){
				if(data.result[0].bindType=="1"){
					qq_bindtype=data.result[0].bindType;
					webo_bindtype=data.result[1].bindType;
					qq_token=data.result[0].token;
					weibo_token=data.result[1].token;
					
//					exports.getQQBind(qq_token);
				}else{
					webo_bindtype=data.result[0].bindType;
					qq_bindtype=data.result[1].bindType;
					qq_token=data.result[1].token;
					weibo_token=data.result[0].token;
					
//					exports.getQQBind(qq_token);
				}
				$("#account-sina-pic").hide();
				$("#remove-sina-bind").show();
				//$("#third-sina-bind").show();
				$("#account-qq-pic").hide();
				$("#remove-qq-bind").show();
				//$("#third-qq-bind").show();
			}else{
				bindtype=data.result[0].bindType;
				if(bindtype=="1"){
					$("#account-qq-pic").hide();
					$("#remove-qq-bind").show();
					//$("#third-qq-bind").show();
					qq_bindtype=data.result[0].bindType;
					qq_token=data.result[0].token;
//					exports.getQQBind(qq_token);
				}else{
					$("#account-sina-pic").hide();
					$("#remove-sina-bind").show();
					//$("#third-sina-bind").show();
					webo_bindtype=data.result[0].bindType;
					weibo_token=data.result[0].token;
//					exports.getBind(weibo_token);
				}
			}
			}
		}).fail(function() {
			
		});
	};
	exports.checkToken();
	//解除绑定
	exports.removeBind=function(e,callback){
		postData={"user":{"id":uid},"bindType":e};
		postData = $.toJSON(postData);
		$.ajax({
			url : $CONFIG.base_url + "/api/user/disbind",
			type : "POST",
			data : postData,
			// dataType : "json",
			contentType : "application/json",
			success : function(data) {
				if (typeof (callback) == "function") {
					callback();
				}
			},
			error : function() {
				$.jBox.tip('解除绑定失败！');
			}
		});
	};
	$("#remove-sina-bind").click(function(){
		var submit = function (v, h, f) {
		    if (v == 'ok')
		    	exports.removeBind(webo_bindtype,function(){
		    		$.jBox.tip('解除绑定成功！');
		    		$("#remove-sina-bind").hide();
		    		$("#account-sina-pic").show();
		    	});
		    else if (v == 'cancel')
		    return true; //close
		};
		$.jBox.confirm("<span style='text-align:center;width:100%;display:block;color: #834313;'>您您是否要解除微博绑定？？</span>", "<span style='text-align:center;width:100%;display:block;color: #834313;'>友情提示</span>", submit);
	});
	
	$("#remove-qq-bind").click(function(){
		var submit = function (v, h, f) {
		    if (v == 'ok')
		    	exports.removeBind(qq_bindtype,function(){
		    		$.jBox.tip('解除绑定成功！');
		    		$("#remove-qq-bind").hide();
		    		$("#account-qq-pic").show();
		    	});
		    else if (v == 'cancel')
		    return true; //close
		};
		$.jBox.confirm("<span style='text-align:center;width:100%;display:block;color: #834313;'>您您是否要解除QQ绑定？？</span>", "<span style='text-align:center;width:100%;display:block;color: #834313;'>友情提示</span>", submit);
	});
	// 个人资料设置
	exports.options.userInforLink = $CONFIG.base_url + "/api/user";
	exports.options.userInforParams = {
		"uid" : uid
	};
	var userInforList = $.get(exports.options.userInforLink,
			exports.options.userInforParams);
	userInforList.done(function(data) {
		var selectKind = template.render('proSetTbody-template', data);
		$('#proSetTbody').empty().append(selectKind);
		var sex = $(".sex").attr('data');
		if (sex == '0') {
			$(".woman").attr("checked", "checked");
		} else {
			$(".man").attr("checked", "checked");
		}
		$("#change-img").click(function() {
			$("#correctPortrait").click();
		});
		$('.column1 input').iCheck({
			radioClass : 'iradio_minimal-yellow',
			checkboxClass : 'iradio_minimal-yellow',
			increaseArea : '-10%', // optional
		});

		$('#correctPortrait').click(function() {
			$(this).fileupload({
				url : $CONFIG.base_url
						+ "/common/attachment/upload/multi",
				dataType : 'json',
				formData : {
					uid : 1,press:"false"
				},
				 add: function (e, data) {
				        var goUpload = true;
				        var uploadFile = data.files[0];
				        if (!(/\.(gif|jpg|jpeg|png)$/i).test(uploadFile.name)) {
				        	$.jBox.tip('亲~请选择正确的图片格式');
				            goUpload = false;
				        }
				        if (uploadFile.size > 1048576) { // 1mb
				        	$.jBox.tip('亲~图片太大了，最大不超过1mb哦！');
				            goUpload = false;
				        }
				        if (goUpload == true) {
				            data.submit();
				        }
				    },
				    progressall : function(e, data) {
						var progress = parseInt(data.loaded / data.total * 100,10);
						$("#loading-load").show();
						$("#loading-load").text(progress + '%');
					},
				done : function(e, data) {
					exports.laoding("file-preview");
					$.each(data.result,function(index,file) {
						
						////console.log(file);
						$(".userAvatar").val(file.id);
						var html = '<img src="'+ $CONFIG.base_url+ '/common/attachment/download/'
								+ file.id
								+ '/100x100"/>';
						$('#file-preview').empty().append(html);
						$('#coverId').val(file.id);
						$("#loading-load").hide();
					});
				}
			});
		});
	});

	$("#proSet").validate({
		ignore : "",
		errorContainer : $("#proSet div.error"),
		errorLabelContainer : $("#proSet div.error"),
		wrapper : 'li'
	});
	
	// 个人信息修改
	$("#proSet").bind("submit", function(e) {
		e.preventDefault();
		if(!$("#proSet").valid()){
			return;
		};
		exports.submitForm("proSet", "/api/user/update/web",function(){
			$.jBox.tip("修改成功");
		});
	});
	// 修改密码
	$('#uid').val($g_user.id);
	$("#pwdSet .account-set").click(function(e) {
		$this = $("#pwdSet");
		if (!$this.valid()) {
			return;
		}
		if($("#newPassword").val().length<6){
			$.jBox.tip("密码不能小于6位");
			return;
		}
		else if($("#newPassword").val().length>16){
			$.jBox.tip("密码不能大于16位");
			return;
		}
		var postDate = form2js('pwdSet', '.', true);
		$.ajax({
			url : $CONFIG.base_url + "/api/user/check_password",
			type : "POST",
			data : postDate,
			contentType : "application/x-www-form-urlencoded",
			success : function(data) {
				//console.log(data);
				if(data=="true"){
					//console.log(postDate);
					$.ajax({
						url : $CONFIG.base_url + "/api/user/update/password",
						type : "POST",
						data : postDate,
						contentType : "application/x-www-form-urlencoded",
						success : function() {
							$.jBox.tip("修改密码成功");
							// 模拟2秒后完成操作
							window.setTimeout(function () { window.location = $CONFIG.base_url+"/logout"; }, 1000);
						},
						error : function() {
							t = "3";
							$.jBox.tip("设置失败！请重试");
							time = setInterval(exports.time,1000);
						}
					});
				}else{
					t = "3";
					$.jBox.tip("原密码错误！请重试");
					time = setInterval(exports.time, 1000);
				};
			},
			error : function() {}
		});
	});
	
	//渲染用户设置
	exports.renderSetting=function(data){
		//console.log(data.userSettings);
		//var iradios=$("#informSet .iradio_minimal-yellow");
		for(var i=0 ;i<data.userSettings.length;i++){
			//console.log("metaValue"+data.userSettings[i].metaValue);
			switch(data.userSettings[i].metaValue)
			{
				case 1:
					//$(iradios[i]).addClass("checked");
					$("input[id="+data.userSettings[i].metaKey+"]").attr({checked:"checked"});
					$("input[id="+data.userSettings[i].metaKey+"]").parent().addClass("checked");
					break;
				case 0:
					//$(iradios[i]).removeClass("checked");
					$("input[id="+data.userSettings[i].metaKey+"]").removeAttr("checked");
					$("input[id="+data.userSettings[i].metaKey+"]").parent().removeClass("checked");
					break;
			}
		}
	};
	exports.options.renderSettingLink=$CONFIG.base_url+"/api/user/get/setting";
	exports.options.renderSettingParams={"uid":$g_user.id};
	var renderSetting=$.get(exports.options.renderSettingLink,exports.options.renderSettingParams);
	renderSetting.done(function(data){exports.renderSetting(data);});
	
	//用户设置表单提交
	$('#informSet').bind('submit',function(e){
		e.preventDefault();
		exports.submitForm('informSet','/api/user/update/setting',exports.renderSetting);
	});
	 $.getJSON($CONFIG.base_url+"/api/user/get/bind/list",{uid:$g_user.id},function(data){
	 	//console.log(data);
		 // for(var i = 0;i < data.result.length;i++){
			//  console.log(data.result[i].id);
		 // }
	});
	// 提交表单
	exports.submitForm = function submitForm(e, v,callback) {
		var json = form2js(e, '.', true);
		var postData = $.toJSON(json);
		console.log(postData);
		$.ajax({
			url : $CONFIG.base_url + v,
			type : "POST",
			data : postData,
			dataType : "json",
			contentType : "application/json",
			success : function(data) {
				t = "3";
				$.jBox.tip("设置成功");
				time = setInterval(exports.time, 1000);
				if(typeof(callback)=="function"){
					callback(data);
				}
				
			},
			error : function() {
				t = "3";
				$.jBox.tip("设置失败！请重试");
				time = setInterval(exports.time, 1000);
			}
		});
	};
	// 定时器
	var t = 3;
	exports.time = function time() {
		t = t - 1;
		if (t < 0) {
			return false;
		}
		if (t == 0) {
			clearInterval(time);
			$(".letter_send_seccuss").hide();
		}
	};
	
	// 收货地址管理
	
	$("#addressbtn").on("click", function() {
		exports.sendTo();
	});
	
	var addresDatas='';
	$.get($CONFIG.base_url + "/api/region/list", {
		p : "1",
		s : "10000",
	}, function(data) {
		addresDatas=data;
	});
	
	exports.sendTo = function() {
		var sendTo = new List();
		sendTo.options.template = "panel-address-template";
		sendTo.options.container = "#panel-address-count";
		sendTo.options.links = {
			"list" : $CONFIG.base_url + '/api/user/sendto/list'
		};
		sendTo.options.params = {
			"uid" : uid
		};
		sendTo.load(function(data) {
			//加载收货地址
			for(var j=0;j<data.result.length;j++){
				var str='';
				var cids=data.result[j].provinceId;
				var cityId=data.result[j].cityId;
				var districtId=data.result[j].districtId;
				for(var i=0;i<addresDatas.result.length;i++){
					var pId=addresDatas.result[i].id;
					if(pId==cids){
						str+=addresDatas.result[i].name;
					}
					if(pId==cityId){
						str+=addresDatas.result[i].name;
					}
					if(pId==districtId){
						str+=addresDatas.result[i].name;
					}
				};
				$("#panel-address-count").find(".address"+j).text(str);
			};
			
			$(".default-address").each(function() {
				var st = $(this).text();
				if (st == 1) {
					$(this).text("默认地址");
				} else if (st == 0) {
					$(this).text("");
				}
			});
			exports.getCityTypeSelect(0, "province");
			$("#region-province-select").change(function() {
				exports.getCityTypeSelect($(this).val(), "city");
				$("#region-province-id").val($(this).val());
			});
			$("#region-city-select").change(function() {
				exports.getCityTypeSelect($(this).val(), "county");
				$("#region-city-id").val($(this).val());
			});
			$("#region-county-select").change(function() {
				$("#region-county-id").val($(this).val());
			});

		});

	};
	
	//页面跳转定位
		var path = window.location.href;
		path = path.substr(path.lastIndexOf("#") + 1);
		if(path == "panel-address"){
			$("#addressbtn").click();
			exports.sendTo();
		}
	
	// 分配城市联动
	exports.getCityTypeSelect = function(parent, type, callback) {
		$.get($CONFIG.base_url + "/api/region/list/parent", {
			parentId : parent
		}, function(data) {
			var i, len = data.length, html = '';
			for (i = 0; i < len; i++) {
				if (i == "0") {
					html += '<option value="' + data[i].id + '" selected>' + data[i].name + '</option>';
					tasktype = data[i].id;
					$("#region-" + type + "-id").val(data[i].id);
				} else {
					html += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
				}
			}
			$("#region-" + type + "-select").empty().append(html);
			switch (type) {
			case "province":
				exports.getCityTypeSelect(tasktype, "city");
				break;
			case "city":
				exports.getCityTypeSelect(tasktype, "county");
				break;
			default:
				break;
			}
			if (typeof (callback) == "function") {
				callback(data);
			}

		});
	};
	// 删除收货地址
	$("#panel-address-count").on("click", ".addre-del", function() {
		var addreId =$(this).attr("data");
		exports.del("/api/user/sendto/del", addreId, function() {
			exports.sendTo();
		});
	});
	
	exports.del = function(url, s, callback) {
		var gorp = (url == "/api/user/sendto/del") ? "GET" : "POST";
		$.jBox("确认删除？", {
			title : "友情提示",
			buttons : {
				"确定" : 1,
				"取消" : -1
			},
			submit : function(v, h, f) {
				if (v == "1") {
					$.ajax({
						url : $CONFIG.base_url + url,
						type : gorp,
						data : {
							"id" : s
						},
						dataType : "json",
						// contentType : "application/json",
						success : function(data) {
							//console.log(data);
							$.jBox.tip("删除成功！");
							if (typeof (callback) == "function") {
								callback();
							}
							;
							$.jBox.close(true);
						},
						error : function() {
							$.jBox.tip("删除失败！");
						}
					});

					return true;
				}
				if (v == "-1") {
					$.jBox.close();
					return false;
				}
			}
		});
	};
	// 添加收货地址
$("#panel-address-count").on("click",".address-btn",function(){
	$(".update-address").hide();
	$(".addto-address").show();
});
	$("#upModal").on("click", ".addto-address", function() {
		var id=$g_user.id;
		$("#user-id").val(id);
		var data = $("#addMessage").serialize();
	var regexp=/^((\(\d{3}\))|(\d{3}\-))?(1[3578]\d{9})$/;//验证手机  
		 if(!((regexp.test($("#applicantPhone").val())))){
				$.jBox.tip("亲～手机号码格式不正确");
				return;
			};
		var formSubmit = $.post($CONFIG.base_url + "/api/user/sendto/add", data);
		formSubmit.done(function(formReturn) {
			$.jBox.tip("添加成功");
			exports.sendTo();
			$("#upModal").modal("hide");
		}).fail(function() {
			$.jBox.tip("添加失败");
			exports.sendTo();
		});
	});
	// 修改送货地址
	$("#panel-address-count").on("click", ".addre-upd", function() {
		$(".update-address").show();
		$(".addto-address").hide();
		var data = $.parseJSON($(this).attr("data"));
		var provinceId=data.provinceId;
		var cityId=data.cityId;
		var districtId=data.districtId;
		$("#addre-id").val(data.id);
		$("#user-uid").val($g_user.id);
		$("#applicantName").val(data.name);
		$("#region-province-select option").each(function() {
			if ($(this).val() == provinceId) {
				$(this).attr("selected", "selected");
				exports.getCityTypeSelect($(this).val(), "city", function() {
					$("#region-city-select option").each(function() {
						if ($(this).val() == cityId) {
							$(this).attr("selected", "selected");
							exports.getCityTypeSelect($(this).val(), "county", function() {
								$("#region-county-select option").each(function() {
									if ($(this).val() == districtId) {
										$(this).attr("selected", "selected");
									};
								});
							});
						};
					});
				});
			};
		});

		$("#appaddress").val(data.endRegion);
		$("#applicantPhone").val(data.phone);
		if (data.isdefault == 0) {
			$("#default-two").attr("checked", true);
		} else if (data.isdefault == 1) {
			$("#default-one").attr("checked", true);
		}
		;
		$("#upModal").modal();
	});
	$("#upModal").on("click",".update-address", function() {
		var regexp=/^((\(\d{3}\))|(\d{3}\-))?(1[3578]\d{9})$/;//验证手机  
		 if(!((regexp.test($("#applicantPhone").val())))){
				$.jBox.tip("亲～手机号码格式不正确");
				return;
			};
		$("#user-uid").val($g_user.id);
		var dat = $("#addMessage").serialize();
		var formSubmit = $.post($CONFIG.base_url + "/api/user/sendto/update", dat);
		formSubmit.done(function(formReturn) {
			$.jBox.tip("修改成功");
			exports.sendTo();
			$("#upModal").modal("hide");
		}).fail(function() {
			$.jBox.tip("修改失败");
			exports.sendTo();
		});
	});
	
});
